package com.rush.manageepac.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.rush.manageepac.dao.Detailsdao;
import com.rush.manageepac.dao.PsmDao;
import com.rush.manageepac.entity.Details;
import com.rush.manageepac.entity.Psm;
import com.rush.manageepac.service.intf.PsmService;
import com.rush.manageepac.util.StringUtil;
import com.rush.manageepac.vo.PageBean;
import com.rush.manageepac.vo.R;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;


@Service
public class PsmServiceImpl implements PsmService {
    private final PsmDao dao;

    public PsmServiceImpl(PsmDao dao) {
        this.dao = dao;
    }

    @Override
    public R save(Psm psm) {
        if (dao.save(psm)>0){
            return R.ok();
        }else {
            return R.fail();
        }
    }

    @Override
    public R update(Psm psm) {
        if (dao.update(psm)>0){
            return R.ok();
        }else {
            return R.fail();
        }
    }

    @Override
    public R delete(int id) {
        if (dao.delete(id)>0){
            return R.ok();
        }
        else {
            return R.fail();
        }
    }
    @Override
    public PageBean selectPage(String name, int page, int limit) {
        if(StringUtil.isNotEmpty(name)){
            name="%"+name+"%";
        }
        int start=(page-1)*limit;

        return PageBean.ok(dao.selectCount(name),dao.selectPage(name,start,limit));
    }

    @Override
    public R delIds(int[] ids) {
        if(dao.delByIds(ids)>0){
            return R.ok();
        }else {
            return R.fail();
        }
    }

    @Override
    public List<Psm> all() {
        return dao.all();
    }

    @Override
    public R upload(MultipartFile file) throws IOException {
        //1.接收文件， 获取文件内容
        //1.验证上传文件是否存在
        if(!file.isEmpty()){
            //2.解析Excel -EasyExcel
            //2.解析Excel数据
            List<Psm> list= EasyExcel.read(file.getInputStream(), Psm.class, new ReadListener() {
                @Override
                public void invoke(Object o, AnalysisContext analysisContext) {}
                @Override
                public void doAfterAllAnalysed(AnalysisContext analysisContext) {}
            }).sheet().doReadSync();
            //3.Mybatis 实现批量新增
            if(dao.saveBatch(list)>0){
                //4.返回
                return R.ok();
            }
        }
        return R.fail();
    }

}
